package cn.iotweb.controller;

import cn.iotweb.model.Source;
import cn.iotweb.model.User;
import cn.iotweb.service.SourceService;
import cn.iotweb.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * 资料控制器
 * Created by WSL on 2016/10/23.
 */
@Controller
public class SourceController {

    @Autowired
    private TagService tagService;
    @Autowired
    private SourceService sourceService;

    /**
     * 资源界面加载控制器
     *
     * @return
     */
    @RequestMapping("/source")
    public String source(HttpServletRequest req, ModelMap model) {
        model.addAttribute("tags", tagService.getAllTags());
        model.addAttribute("sources", sourceService.getSourceWithOption("0"));
        model.addAttribute("downloadOrder", sourceService.getDownloadOrder());
        model.addAttribute("timeOrder", sourceService.getTimeOrder());
        return "view/source";
    }

    /**
     * 搜索资源控制器
     *
     * @throws IOException
     */
    @RequestMapping("/searchSource")
    @ResponseBody
    public List<Source> sourchSearch(@RequestParam("keyword") String keyword) throws IOException {
        return sourceService.searchSource(keyword);
    }

    /**
     * 根据条件获取资源
     *
     * @param tagids 标签集合
     * @return
     */
    @RequestMapping("/getSource")
    @ResponseBody
    public List<Source> getSource(@RequestParam("tagids") String tagids, HttpServletResponse resp) throws IOException {
        System.out.print(tagids);
        if (null == tagids || "" == tagids)
            return new LinkedList<Source>();
        return sourceService.getSourceWithOption(tagids);
    }

    /**
     * 获得下载量排名
     *
     * @return
     */
    @RequestMapping("/getDownloadOrder")
    @ResponseBody
    public List<Source> getDownloadOrder() throws IOException {
        return sourceService.getDownloadOrder();
    }

    /**
     * 获得时间排名
     *
     * @return
     */
    @RequestMapping("/getTimeOrder")
    @ResponseBody
    public List<Source> getTimeOrder() throws IOException {
        return sourceService.getTimeOrder();
    }
}
